import { assetManager, AssetManager } from 'cc';

export class BundleManager {
    private static _instance: BundleManager;
    public static get instance(): BundleManager {
        if (!this._instance) {
            this._instance = new BundleManager();
        }
        return this._instance;
    }

    private constructor() {}

    private bundleCache: Map<string, any> = new Map();

    /**
     * 加载分包（全局缓存，已加载直接返回）
     * @param bundleName 分包名称
     * @returns Promise<AssetManager.Bundle>
     */
    public async loadBundle(bundleName: string): Promise<any> {
        if (this.bundleCache.has(bundleName)) {
            return this.bundleCache.get(bundleName);
        }
        return new Promise((resolve, reject) => {
            assetManager.loadBundle(bundleName, (err, bundle) => {
                if (err) {
                    reject(err);
                } else {
                    this.bundleCache.set(bundleName, bundle);
                    resolve(bundle);
                }
            });
        });
    }

    /**
     * 主动释放指定 bundle
     */
    public releaseBundle(bundleName: string) {
        if (this.bundleCache.has(bundleName)) {
            const bundle = this.bundleCache.get(bundleName);
            assetManager.removeBundle(bundle);
            this.bundleCache.delete(bundleName);
        }
    }

    /**
     * 释放所有 bundle
     */
    public releaseAllBundles() {
        for (const [bundleName, bundle] of this.bundleCache.entries()) {
            assetManager.removeBundle(bundle);
        }
        this.bundleCache.clear();
    }
} 